﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace server
{
    public static class HexTool
    {
        public static byte[] CalcTranHash(ulong height, byte[] roothash, byte[] data)
        {
            var fdata =BitConverter.GetBytes(height).Concat(roothash).Concat(data).ToArray();
            return CalcHash(fdata);
        }
        public static byte[] CalcRootHash(byte[] oldroothash, byte[] newnodehash)
        {
            var fdata= oldroothash.Concat(newnodehash).ToArray();
            return CalcHash(fdata);
        }
        public static bool HexEqual(byte[] a, byte[] b)
        {
            if (a == null || b == null)
                throw new Exception("cant null");
            if (a.Length != b.Length)
                return false;
            for (var i = 0; i < a.Length; i++)
                if (a[i] != b[i]) 
                    return false;
            return true;
        }
        public static string Hex2Str(byte[] data)
        {
            string str = "";
            foreach (var c in data)
            {
                str += c.ToString("X02");
            }
            return str;
        }
        public static byte[] Str2Hex(string str)
        {
            var data = new byte[str.Length / 2];
            for (var i = 0; i < data.Length; i++)
            {
                data[i] = byte.Parse(str.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
            }
            return data;
        }
        [ThreadStatic]
        static SHA256 sha256;
        public static byte[] CalcHash(byte[] data)
        {
            if (sha256 == null)
                sha256 = SHA256.Create();
            return sha256.ComputeHash(data);
        }
    }
}
